<template>
	<div class="order-container">
		<!-- 自定义导航栏 -->
		<div class="custom-navbar">
			<div class="nav-title">我的订单</div>
		</div>

		<!-- 加载状态 -->
		<div v-if="loading" class="loading">
			<i class="fas fa-spinner fa-spin"></i> 加载中...
		</div>

		<!-- 订单列表 -->
		<div v-else class="order-list">
			<div v-for="(order, index) in orderList" :key="index" class="order-item">
				<!-- 订单头部信息 -->
				<div class="order-header">
					<div class="order-time">
						<div class="time-label">下单时间：</div>
						<div class="time-value">{{ formatTime(order.createTime) }}</div>
						<div class="order-number">订单号: {{ order.orderNumber }}</div>
					</div>
					<div class="order-status" :class="getOrderStatusClass(order)">
						{{ getOrderStatusText(order) }}
					</div>
				</div>

				<!-- 订单内容 - 默认显示前2个菜品 -->
				<div class="order-content">
					<div v-for="(dish, dishIndex) in order.dishItems.slice(0, 2)" :key="dishIndex" class="dish-item">
						<!-- 菜品图片 -->
						<img class="dish-image" :src="getDishImage(dish.image)" :alt="dish.dishName">

						<!-- 菜品信息 -->
						<div class="dish-info">
							<div class="dish-name">{{ dish.dishName }}</div>
							<div class="dish-price">¥{{ dish.price.toFixed(2) }}</div>
						</div>

						<div class="dish-quantity">x{{ dish.quantity }}</div>
						<div class="dish-subtotal">¥{{ dish.subtotal.toFixed(2) }}</div>
					</div>

					<!-- 折叠/展开区域 -->
					<div class="expandable-content" :class="{expanded: order.expanded}">
						<div v-for="(dish, dishIndex) in order.dishItems.slice(2)" :key="dishIndex + 2"
							class="dish-item">
							<!-- 菜品图片 -->
							<img class="dish-image" :src="getDishImage(dish.image)" :alt="dish.dishName">

							<!-- 菜品信息 -->
							<div class="dish-info">
								<div class="dish-name">{{ dish.dishName }}</div>
								<div class="dish-price">¥{{ dish.price.toFixed(2) }}</div>
							</div>

							<div class="dish-quantity">x{{ dish.quantity }}</div>
							<div class="dish-subtotal">¥{{ dish.subtotal.toFixed(2) }}</div>
						</div>
					</div>

					<!-- 展开/收起按钮 -->
					<div v-if="order.dishItems.length > 2" class="expand-toggle" @click="toggleExpand(order)">
						{{ order.expanded ? '收起详情' : `查看全部${order.dishItems.length}个菜品` }}
						<div class="expand-icon" :class="{expanded: order.expanded}">▼</div>
					</div>
				</div>

				<!-- 订单底部 -->
				<div class="order-footer">
					<div class="order-total">
						<div class="total-label">合计：</div>
						<div class="total-amount">¥{{ order.totalAmount.toFixed(2) }}</div>
					</div>
					<div class="order-actions">
						<button v-if="order.orderState !== 1 && order.payState === 0" class="action-btn pay-btn"
							@click="payOrder(order.id)">去支付</button>
						<button v-if="order.orderState !== 1 && order.payState === 0" class="action-btn cancel-btn"
							@click="cancelOrder(order.id)">取消订单</button>
					</div>
				</div>
			</div>
		</div>

		<!-- 空状态 -->
		<div v-if="!loading && orderList.length === 0" class="empty-state">
			<svg class="empty-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
				stroke="currentColor" stroke-width="1">
				<path d="M6 2L3 6v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V6l-3-4H6zM3.8 6h16.4M16 10a4 4 0 1 1-8 0" />
			</svg>
			<div class="empty-text">暂无订单记录</div>
			<button class="go-shopping-btn" @click="goShopping">去逛逛</button>
		</div>
	</div>
</template>

<script>
	import {
		ref,
		onMounted
	} from 'vue';

	export default {
		name: 'OrderList',
		setup() {
			const orderList = ref([]);
			const loading = ref(true);
			const error = ref(null);
			const userId = ref(null); // 添加用户ID变量
			// 请求函数
			async function request(url, method = 'post', data = {}) {
				return new Promise((resolve, reject) => {
					// 实际项目中这里应该是真实的API请求
					// 使用uni.request或axios等HTTP客户端
					uni.request({
						url: 'http://localhost:8080' + url,
						method,
						data,
						success: (res) => {
							resolve(res.data);
						},
						fail: (err) => {
							reject(err);
						}
					});
				});
			};
			// 获取用户ID
			const getUserId = () => {
				try {
					// 从本地存储获取用户信息
					const userInfo = uni.getStorageSync('userInfo');
					if (userInfo && userInfo.id) {
						return userInfo.id;
					} else {
						// 如果没有用户信息，尝试从全局状态获取
						if (typeof getApp === 'function') {
							const app = getApp();
							if (app && app.globalData && app.globalData.userInfo) {
								return app.globalData.userInfo.id;
							}
						}
						return null;
					}
				} catch (e) {
					console.error('获取用户ID失败:', e);
					return null;
				}
			};

			// 获取订单列表
			const fetchOrderList = async () => {
				try {
					loading.value = true;
					error.value = null;

					// 获取用户ID
					userId.value = getUserId();
					if (!userId.value) {
						throw new Error('无法获取用户信息，请重新登录');
					}

					const response = await request('/t-order/person_orderList', 'POST', {
						userId: userId.value
					});
					console.log(response)
					if (response.code === 200) {
						// 添加expanded属性用于控制展开/收起
						orderList.value = response.data.map(order => ({
							...order,
							expanded: false
						}));
					} else {
						throw new Error(response.msg || '获取订单列表失败');
					}
				} catch (err) {
					console.error('获取订单列表失败:', err);

					error.value = err.message || '获取订单列表失败';
					uni.showToast({
						title: error.value,
						icon: 'none',
						duration: 3000
					});
				} finally {
					loading.value = false;
				}
			};

			// 格式化时间
			const formatTime = (timeString) => {
				const date = new Date(timeString);
				const year = date.getFullYear();
				const month = date.getMonth() + 1;
				const day = date.getDate();
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');

				return `${year}-${month}-${day} ${hour}:${minute}`;
			};

			// 获取订单状态文本
			const getOrderStatusText = (order) => {
				// 如果订单状态为0，表示已取消
				if (order.orderState === 1) {
					return '已取消';
				}
				// 否则根据支付状态显示
				switch (order.payState) {
					case 0:
						return '未支付';
					case 1:
						return '已支付';
					default:
						return '未知状态';
				}
			};

			// 获取订单状态样式类
			const getOrderStatusClass = (order) => {
				// 如果订单状态为0，表示已取消
				if (order.orderState === 0) {
					return 'status-cancelled';
				}
				// 否则根据支付状态显示
				switch (order.payState) {
					case 0:
						return 'status-unpaid';
					case 1:
						return 'status-paid';
					default:
						return '';
				}
			};

			// 在script部分添加或修改getDishImage方法
			const getDishImage = (imageData) => {
				// 如果没有图片数据，返回默认图片
				if (!imageData) {
					return '/static/default-dish.png'; // 替换为你的默认图片路径
				}

				// 如果已经是完整的URL（包含http或data:），直接返回
				if (imageData.startsWith('http') || imageData.startsWith('data:')) {
					return imageData;
				}

				// 如果是Base64编码（没有前缀），添加适当的前缀
				if (imageData.length > 0 && !imageData.startsWith('data:')) {
					// 检测图片类型（简单判断）
					let mimeType = 'image/jpeg'; // 默认JPEG

					// Base64编码的PNG通常以iVBORw开头
					if (imageData.startsWith('iVBORw')) {
						mimeType = 'image/png';
					}
					// Base64编码的GIF通常以R0lGOD开头
					else if (imageData.startsWith('R0lGOD')) {
						mimeType = 'image/gif';
					}
					// Base64编码的WebP通常以UklGR开头
					else if (imageData.startsWith('UklGR')) {
						mimeType = 'image/webp';
					}

					return `data:${mimeType};base64,${imageData}`;
				}

				// 其他情况返回默认图片
				return '/static/default-dish.png';
			};


			// 支付订单
			const payOrder = (orderId) => {
				uni.showModal({
					title: '确认支付',
					content: '确定要支付此订单吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const response = await request('/t-order/pay_order', 'POST', {
									id: orderId
								});
								if (response.code === 200) {
									uni.showToast({
										title: '支付成功',
										icon: 'success'
									});
									// 重新加载订单列表
									fetchOrderList();
								} else {
									uni.showToast({
										title: response.msg || '支付失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.log('支付订单失败:', error);
								uni.showToast({
									title: '支付失败',
									icon: 'none'
								});
							}
						}
					}
				});
			};

			// 取消订单
			const cancelOrder = (orderId) => {
				uni.showModal({
					title: '确认取消',
					content: '确定要取消此订单吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								const response = await request('/t-order/cancel_order', 'POST', {
									id: orderId
								});
								if (response.code === 200) {
									uni.showToast({
										title: '订单已取消',
										icon: 'success'
									});
									// 重新加载订单列表
									fetchOrderList();
								} else {
									uni.showToast({
										title: response.msg || '取消失败',
										icon: 'none'
									});
								}
							} catch (error) {
								console.log('取消订单失败:', error);
								uni.showToast({
									title: '取消失败',
									icon: 'none'
								});
							}
						}
					}
				});
			};

			// 查看订单详情
			const viewOrderDetail = (orderId) => {
				uni.navigateTo({
					url: `/pages/orderDetail/orderDetail?orderId=${orderId}`
				});
			};

			// 去购物
			const goShopping = () => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			};

			// 切换展开状态
			const toggleExpand = (order) => {
				order.expanded = !order.expanded;
			};

			onMounted(() => {
				fetchOrderList();
			});

			return {
				orderList,
				loading,
				formatTime,
				getOrderStatusText,
				getOrderStatusClass,
				getDishImage,
				payOrder,
				cancelOrder,
				viewOrderDetail,
				goShopping,
				toggleExpand
			};
		}
	};
</script>

<style scoped>
	.order-container {
		padding-bottom: 20px;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	.custom-navbar {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 50px;
		padding: 0 15px;
		background-color: #ff5722;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
	}

	.nav-title {
		font-size: 18px;
		font-weight: bold;
	}

	.order-list {
		padding: 15px;
	}

	.order-item {
		background-color: #fff;
		border-radius: 12px;
		margin-bottom: 15px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		overflow: hidden;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		border-bottom: 1px solid #f0f0f0;
	}

	.order-time {
		font-size: 14px;
		color: #666;
	}

	.time-label {
		color: #999;
		display: inline;
	}

	.order-status {
		font-size: 14px;
		font-weight: bold;
		padding: 4px 10px;
		border-radius: 20px;
	}

	.status-unpaid {
		color: #ff9900;
		background-color: rgba(255, 153, 0, 0.1);
	}

	.status-paid {
		color: #19be6b;
		background-color: rgba(25, 190, 107, 0.1);
	}

	.status-cancelled {
		color: #ff4d4f;
		background-color: rgba(255, 77, 79, 0.1);
	}


	.order-content {
		padding: 15px;
	}

	.dish-item {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
	}

	.dish-item:last-child {
		margin-bottom: 0;
	}

	.dish-image {
		width: 60px;
		height: 60px;
		border-radius: 8px;
		margin-right: 15px;
		flex-shrink: 0;
		object-fit: cover;
		background-color: #f5f5f5;
	}

	.dish-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.dish-name {
		font-size: 15px;
		color: #333;
		margin-bottom: 5px;
		font-weight: 500;
	}

	.dish-price {
		font-size: 13px;
		color: #999;
	}

	.dish-quantity {
		font-size: 14px;
		color: #666;
		margin: 0 15px;
	}

	.dish-subtotal {
		font-size: 15px;
		color: #333;
		font-weight: bold;
	}

	.expandable-content {
		max-height: 0;
		overflow: hidden;
		transition: max-height 0.3s ease;
	}

	.expandable-content.expanded {
		max-height: 1000px;
	}

	.expand-toggle {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10px 0;
		color: #007AFF;
		font-size: 14px;
	}

	.expand-icon {
		margin-left: 5px;
		transition: transform 0.3s ease;
	}

	.expand-icon.expanded {
		transform: rotate(180deg);
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		border-top: 1px solid #f0f0f0;
	}

	.order-total {
		font-size: 14px;
		color: #666;
		display: flex;
		align-items: center;
	}

	.total-amount {
		font-size: 18px;
		color: #ff5722;
		font-weight: bold;
		margin-left: 5px;
	}

	.order-actions {
		display: flex;
	}

	.action-btn {
		margin-left: 10px;
		font-size: 14px;
		padding: 0 15px;
		height: 32px;
		line-height: 32px;
		border-radius: 16px;
		border: none;
		outline: none;
	}

	.pay-btn {
		background-color: #ff5722;
		color: #fff;
	}

	.cancel-btn {
		background-color: #fff;
		color: #666;
		border: 1px solid #ddd;
	}

	.detail-btn {
		background-color: #fff;
		color: #333;
		border: 1px solid #ddd;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 60px 20px;
		text-align: center;
	}

	.empty-icon {
		width: 120px;
		height: 120px;
		margin-bottom: 20px;
		opacity: 0.6;
	}

	.empty-text {
		font-size: 16px;
		color: #999;
		margin-bottom: 30px;
	}

	.go-shopping-btn {
		background-color: #ff5722;
		color: #fff;
		border: none;
		border-radius: 20px;
		padding: 0 30px;
		height: 40px;
		line-height: 40px;
		font-size: 14px;
	}

	.loading {
		text-align: center;
		padding: 30px;
		color: #999;
		font-size: 14px;
	}

	.order-number {
		font-size: 12px;
		color: #999;
		margin-top: 5px;
	}
</style>